package com.fy.module.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.common.util.JwtUtils;
import com.fy.common.util.RsaUtils;
import com.fy.common.vo.ResultVo;
import com.fy.module.user.UserDto;
import com.fy.module.user.entity.User;
import com.fy.module.user.mapper.UserMapper;
import com.fy.module.user.mapper.UserRoleMapper;
import com.fy.module.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.security.PrivateKey;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Autowired
    private UserRoleMapper roleMapper;

//    @Autowired
//    private SysPermissionMapper sysPermissionMapper;

    @Override
    public ResultVo<String> login(UserDto user) {

        if(user == null){
            return new ResultVo<>(false, "非法参数");
        }

        User userDB = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", user.getUserName()));
        if(userDB == null) return new ResultVo<>(false, "用户名或密码不正确");

        //比较密码
        boolean matches = encoder.matches(user.getPassword(), userDB.getPassword());
        if (!matches) return new ResultVo<>(false, "用户名或密码不正确");

        //颁发令牌之前，获取用户的角色，用户的权限
        List<String> roles =
                roleMapper.findRolesByUserId(userDB.getUserId() + "");

//        List<String> permissions = sysPermissionMapper.findPermissionByUserId(userDB.getUserId() + "");
//        String rolePermission = StrUtil.join(",", roles, permissions);
        String rolePermission = StrUtil.join(",", roles);
        userDB.setRolePermisson(rolePermission);

        PrivateKey privateKey = null;
        try {
            //颁发jwt 令牌
//            privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:pri_rsa").getPath());
            privateKey = RsaUtils.getPrivateKey(RsaUtils.readBytes3(new ClassPathResource("pri_rsa").getInputStream()));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String jwtToken = JwtUtils.generateTokenExpireInMinutes(userDB, privateKey, 30 * 60);


        return new ResultVo<>(true, "success", jwtToken);
    }

}
